// 新的方式
import { createSlice, createAsyncThunk, } from "@reduxjs/toolkit";
import { getHomeGoodPriceInfo, getHomeHighScoreInfo, getHomeDiscountInfo, getHomeRecommendInfo, getHomeLongforInfo, getHomePlusData } from "@/service";

// 获取异步数据
// 单个异步请求Action
// export const fetchHomeDataAction = createAsyncThunk('fetchdata', async ({payload}) => {
//   const res = await getHomeGoodPriceInfo()
//   console.log('home', res)
//   return res
// })

// 多个异步请求Action
export const fetchHomeDataAction = createAsyncThunk('fetchdata', (payload, {dispatch}) => {
  getHomeGoodPriceInfo().then(res => dispatch(changeGoodPriceInfoAction(res)))
  getHomeHighScoreInfo().then(res => dispatch(changeHighScoreInfoAction(res)))
  getHomeDiscountInfo().then(res => dispatch(changeDiscountInfoAction(res)))
  getHomeRecommendInfo().then(res => dispatch(changeRecommendInfoAction(res)))
  getHomeLongforInfo().then(res => dispatch(changeLongforInfoAction(res)))
  getHomePlusData().then(res => dispatch(changePlusDataAction(res)))
})

const homeSlice = createSlice({
  name: 'home',
  initialState: {
    goodPriceInfo: {},
    highScoreInfo: {},
    discountInfo: {},
    recommendInfo: {},
    longforInfo: {},
    plusData: {}
  },
  reducers: {
    changeGoodPriceInfoAction(state, {payload}) {
      state.goodPriceInfo = payload
    },
    changeHighScoreInfoAction(state, {payload}) {
      state.highScoreInfo = payload
    },
    changeDiscountInfoAction(state, {payload}) {
      state.discountInfo = payload
    },
    changeRecommendInfoAction(state, {payload}) {
      state.recommendInfo = payload
    },
    changeLongforInfoAction(state, {payload}) {
      state.longforInfo = payload
    },
    changePlusDataAction(state, {payload}) {
      state.plusData = payload
    }
  },
  extraReducers: (builder) => {
    // builder.addCase(fetchHomeDataAction.fulfilled, (state, { payload }) => {
    //   state.goodPriceInfo = payload
    // })
  }
})

export const { 
  changeGoodPriceInfoAction, 
  changeHighScoreInfoAction,
  changeDiscountInfoAction,
  changeRecommendInfoAction,
  changeLongforInfoAction,
  changePlusDataAction } = homeSlice.actions
export default homeSlice.reducer